package com.atguigu.champter8;

import com.atguigu.beans.UserBehavior;
import com.atguigu.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;

//实时统计每小时内的网站PV
public class Flink01_Project_High_PV {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .readTextFile("datas/input/UserBehavior.csv")
                .map(line ->{
                    String[] data = line.split(",");
                    return new UserBehavior(Long.valueOf(data[0]),Long.valueOf(data[1]),Integer.valueOf(data[2]),data[3],Long.parseLong(data[4])*1000);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                        .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((ele,ts) ->ele.getTimestamp())
                )
                .filter(new FilterFunction<UserBehavior>() {
                    @Override
                    public boolean filter(UserBehavior value) throws Exception {
                        return "pv".equals(value.getBehavior());
                    }
                })
                .keyBy(UserBehavior::getBehavior)
                .window(TumblingEventTimeWindows.of(Time.minutes(30)))
                .process(new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                       Context ctx,
                                        Iterable<UserBehavior> elements,
                                        Collector<String> out) throws Exception {

                        int pv = AtguiguUtil.toList(elements).size();
                        Date start = new Date(ctx.window().getStart());
                        Date end = new Date(ctx.window().getEnd());
                        out.collect(start + " " + end + " " + pv);
                    }
                }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
